import * as AWS from "aws-sdk";
import * as fs from "fs";

interface STSCredentials {
    accessKeyId: string;
    secretAccessKey: string;
    sessionToken: string;
}

// 上传文件到S3
async function uploadFileToS3(file: string, stsCredentials: STSCredentials) {
    AWS.config.credentials = new AWS.Credentials(
        stsCredentials.accessKeyId,
        stsCredentials.secretAccessKey,
        stsCredentials.sessionToken
    );

    const s3 = new AWS.S3({
        region: "ap-east-1", // 替换成S3 Bucket所在的AWS区域
    });

    const fileStream = fs.createReadStream(file);

    const params = {
        Bucket: "pump404-test-s3", // 替换成Bucket名称
        Key: "/tmp/uploads/comment/20240711/user666.png",  // 文件将上传到S3的指定目录
        Body: fileStream,
    };

    try {
        const data = await s3.upload(params).promise();
        console.log("File uploaded successfully:", data.Location);
    } catch (err) {
        console.error("Error uploading file:", err);
    }
}

// 获取STS凭证并上传文件
// 约定：
// 临时文件目录为bucket中的/tmp/uploads/，正式目录为/uploads/
// 路径格式：/uploads/模块名/当天年月日/文件名.扩展名
//         模块名取值：token、comment、user
// 数据表中不保存http开头的绝对路径
async function uploadFile() {
    try {
        // 从后端获取STS凭证
        // const response = await fetch("http://127.0.0.1:8088/api/common/sts");
        // if (!response.ok) {
        //     throw new Error("Failed to fetch STS credentials");
        // }
        // const stsCredentials = await response.json();

        const stsCredentials = {
            accessKeyId: "ASIAYMFXBOLEAW7JYKOS",
            secretAccessKey: "6M6bwas2QQ9yuPzIJFrJpRLoPHnSJ1GbLzbFjhf5",
            sessionToken: "IQoJb3JpZ2luX2VjEJP//////////wEaCWFwLWVhc3QtMSJIMEYCIQDeKFIKyjqJvCasw8YTAFiHE13ViyhhKsJZ2NCNBFiptQIhAPo7FGMbqia1mdh5vo9xp4osvIenE16WuBBhA8QzmoaZKtMBCFwQARoMNTc1OTA5NDkxNDAwIgzib+ud5MQCirwUdU0qsAHYa2qLyVt8hhjXNxuDiEewRlo11ut4p0ehmzHVKKOb1Sb7RPaYOd3Tnl2tA8lJ6B8r516P6D4Yt9juT+NT4xgzFg2UruAUfV4l1WcT8iWeQsdOWjfH7CdQ6Ndmr07ZhvJP84D+iEIiGQr1JxohR3MZYkEOXoN8nmcLr31STihxe/C+Xca8YpB7r0OHkuae8mQT4J4+KApFeFUHHkTJ8Xb+mSUHqmfwHx+FyzdS7RD6WzDq/r60BjqXAQ7iZ0/9OTwdfOXTXc2rXZksKyF5dOPnXA2E6M0FqXYKbmjiErwuwRT0a+i9Iw33VCS4NVxc4bygQWmLdV5No8ZgAcShXOPUSRcWysuOlrZ0nDXbFIQ3efnoxSAzM+pib0rQTt4ogMjCtnlloRzrc3s+pwvgcjo4A6tOihCyulKnaZJbJHRQtgdcuQNj70mWQA9wCeGBlW0="
        };

        const filePath = "./uploads/comment/20240711/user666.png"; // 替换成实际图片路径

        // 上传图片文件到S3
        await uploadFileToS3(filePath, stsCredentials);

    } catch (error) {
        console.error("Error uploading file:", error);
    }
}

// 调用示例：开始上传文件
uploadFile();
